Page({
  data: {
    courseId: null,
    courseName: '',
    className: '',
    studentList: [],
    isLoading: true,
    isSaving: false,
    hasModified: false,
    // 统计数据
    totalStudents: 0,
    enteredCount: 0,
    passCount: 0,
    excellentCount: 0
  },
  
  onLoad: function(options) {
    console.log('接收到的参数:', options); // 添加日志查看实际接收的参数
    
    // 修改参数获取逻辑，兼容多种可能的参数名
    const courseId = options.id || options.courseId;
    
    if (courseId) {
      this.setData({
        courseId: courseId
      });
      // 获取课程学生列表
      this.fetchStudentList();
    } else {
      // 如果没有参数，直接加载模拟数据
      this.loadMockData();
      wx.showToast({
        title: '参数错误，使用模拟数据',
        icon: 'none'
      });
    }
  },
  
  // 获取课程学生列表
  fetchStudentList: function() {
    wx.showLoading({
      title: '加载中...',
    });
    
    wx.request({
      url: `http://localhost:3000/api/courses/${this.data.courseId}/students`,
      method: 'GET',
      header: {
        'Authorization': wx.getStorageSync('token')
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.statusCode === 200) {
          this.setData({
            courseName: res.data.courseName || '',
            className: res.data.className || '',
            studentList: res.data.students || [],
            isLoading: false
          });
          
          // 更新统计数据
          this.updateStats();
        } else {
          // 请求失败，加载模拟数据
          this.loadMockData();
          wx.showToast({
            title: '使用模拟数据',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        // 网络请求失败，加载模拟数据
        this.loadMockData();
        wx.showToast({
          title: '网络错误，使用模拟数据',
          icon: 'none'
        });
      }
    });
  },
  
  // 加载模拟数据
  loadMockData: function() {
    // 模拟数据
    const mockStudents = [
      { id: 1, name: '张三', studentId: '2023001', score: '85' },
      { id: 2, name: '李四', studentId: '2023002', score: '92' },
      { id: 3, name: '王五', studentId: '2023003', score: '78' },
      { id: 4, name: '赵六', studentId: '2023004', score: '65' },
      { id: 5, name: '钱七', studentId: '2023005', score: '59' },
      { id: 6, name: '孙八', studentId: '2023006', score: '88' },
      { id: 7, name: '周九', studentId: '2023007', score: '76' },
      { id: 8, name: '吴十', studentId: '2023008', score: '94' },
      { id: 9, name: '郑十一', studentId: '2023009', score: '' },
      { id: 10, name: '王十二', studentId: '2023010', score: '82' }
    ];
    
    this.setData({
      courseName: '高等数学',
      className: '计算机科学1班',
      studentList: mockStudents,
      isLoading: false
    });
    
    // 更新统计数据
    this.updateStats();
  },
  
  // 更新统计数据
  updateStats: function() {
    if (!this.data.studentList || this.data.studentList.length === 0) {
      return;
    }
    
    const totalStudents = this.data.studentList.length;
    let enteredCount = 0;
    let passCount = 0;
    let excellentCount = 0;
    
    this.data.studentList.forEach(item => {
      if (item.score !== '' && item.score !== null) {
        enteredCount++;
        const score = parseFloat(item.score);
        if (score >= 60) {
          passCount++;
        }
        if (score >= 90) {
          excellentCount++;
        }
      }
    });
    
    this.setData({
      totalStudents: totalStudents,
      enteredCount: enteredCount,
      passCount: passCount,
      excellentCount: excellentCount
    });
  },
  
  // 输入成绩
  inputScore: function(e) {
    const index = e.currentTarget.dataset.index;
    const value = e.detail.value;
    
    // 验证输入是否为有效数字
    if (value !== '' && (isNaN(value) || value < 0 || value > 100)) {
      wx.showToast({
        title: '请输入0-100的有效分数',
        icon: 'none'
      });
      return;
    }
    
    // 更新学生成绩
    const studentList = this.data.studentList;
    studentList[index].score = value;
    
    this.setData({
      studentList: studentList,
      hasModified: true
    });
    
    // 更新统计数据
    this.updateStats();
  },
  
  // 计算GPA
  calculateGPA: function(score) {
    if (score >= 90) return 4.0;
    if (score >= 85) return 3.7;
    if (score >= 80) return 3.3;
    if (score >= 75) return 3.0;
    if (score >= 70) return 2.7;
    if (score >= 65) return 2.3;
    if (score >= 60) return 2.0;
    return 0;
  },
  
  // 保存成绩
  saveGrades: function() {
    // 检查是否有未完成的成绩
    const incompleteStudents = this.data.studentList.filter(student => student.score === '' || student.score === null);
    
    if (incompleteStudents.length > 0) {
      wx.showModal({
        title: '提示',
        content: `有${incompleteStudents.length}名学生的成绩未录入，是否继续保存？`,
        success: (res) => {
          if (res.confirm) {
            this.submitGrades();
          }
        }
      });
    } else {
      this.submitGrades();
    }
  },
  
  // 提交成绩到服务器
  submitGrades: function() {
    this.setData({
      isSaving: true
    });
    
    // 准备提交的数据
    const gradesData = this.data.studentList.map(student => ({
      studentId: student.id,
      score: student.score === '' ? null : parseFloat(student.score),
      gpa: student.score === '' ? null : this.calculateGPA(parseFloat(student.score))
    }));
    
    wx.showLoading({
      title: '保存中...',
    });
    
    // 模拟保存成功
    setTimeout(() => {
      wx.hideLoading();
      this.setData({
        isSaving: false,
        hasModified: false
      });
      
      wx.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 2000
      });
      
      // 延迟返回上一页
      setTimeout(() => {
        wx.navigateBack();
      }, 2000);
    }, 1500);
    
    // 实际网络请求代码（暂时注释）
    /*
    wx.request({
      url: `http://localhost:3000/api/courses/${this.data.courseId}/grades`,
      method: 'POST',
      header: {
        'Authorization': wx.getStorageSync('token'),
        'Content-Type': 'application/json'
      },
      data: {
        grades: gradesData
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.statusCode === 200) {
          this.setData({
            isSaving: false,
            hasModified: false
          });
          
          wx.showToast({
            title: '保存成功',
            icon: 'success',
            duration: 2000
          });
          
          // 延迟返回上一页
          setTimeout(() => {
            wx.navigateBack();
          }, 2000);
        } else {
          this.setData({
            isSaving: false
          });
          
          wx.showToast({
            title: res.data.message || '保存失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        
        this.setData({
          isSaving: false
        });
        
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
    */
  },
  
  // 返回上一页
  goBack: function() {
    if (this.data.hasModified) {
      wx.showModal({
        title: '提示',
        content: '有未保存的修改，确定要离开吗？',
        success: (res) => {
          if (res.confirm) {
            wx.navigateBack();
          }
        }
      });
    } else {
      wx.navigateBack();
    }
  }
})